package com.ywl.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author DL5O
 * @version 1.0
 * 全局异常处理（推荐使用）
 */
/*
@ControllerAdvice注解是Spring3.2中新增的注解，
学名是Controller增强器，作用是给Controller控制器添加统一的操作或处理。
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理SQLIntegrityConstraintViolationException 异常处理
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        //1.判断异常信息中是否包含 Duplicate
        String message = ex.getMessage();
        String[] splitStr = {};
        String str = "";
        if (message.contains("Duplicate")) {
            //异常信息格式：Duplicate entry 'com.ywl' for key 'idx_username'
            splitStr = message.split(" ");
            str = splitStr[2] + "不可重复";
            log.error(str);
        }
        return R.error("失败:" + str);
    }


    /**
     * 处理CustomException 异常处理,处理删除分类时，有菜品和他想关联
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage());
        String message = ex.getMessage();
        return R.error(message);
    }
}
